package com.yunhai.device.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yunhai.common.utils.JwtUtils;
import com.yunhai.device.service.UserRedisService;
import com.yunhai.model.entity.ums.UmsUser;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class UserRedisServiceImpl implements UserRedisService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    private static final String USER_KEY_PREFIX = "user:";
    private static final long USER_EXPIRE_TIME = JwtUtils.JWT_TTL; // 30分钟


    // 存储用户信息
    public void saveUser(UmsUser user) throws JsonProcessingException {
        String key = USER_KEY_PREFIX + user.getId();
;        String value = JSON.toJSONString(user);
        redisTemplate.opsForValue().set(key, value, USER_EXPIRE_TIME, TimeUnit.MINUTES);
    }

    // 获取用户信息
    public UmsUser getUser(String userId) throws JsonProcessingException {
        String key = USER_KEY_PREFIX + userId;
        String value = redisTemplate.opsForValue().get(key);
        if (value == null) {
            return null;
        }
        return JSON.parseObject(value, UmsUser.class);
    }

    // 删除用户信息
    public void deleteUser(String userId) {
        String key = USER_KEY_PREFIX + userId;
        redisTemplate.delete(key);
    }

    // 更新用户过期时间
    public void updateExpire(String userId) {
        String key = USER_KEY_PREFIX + userId;
        redisTemplate.expire(key, USER_EXPIRE_TIME, TimeUnit.MINUTES);
    }
}
